package com.wgke.bluetooth.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.wgke.bluetooth.R;

public class GradientColorView extends View {
    private Paint paint;
    private float value = 0.5f; // 默认值为中间值
    private int[] colors;
    private float[] positions;

    private float cornerRadius;
    private Path roundedRectPath;

    private RectF rectF;
    private int currentColor;

    public GradientColorView(Context context) {
        super(context);
        init();
    }

    public GradientColorView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public GradientColorView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);

        cornerRadius = TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP,
                3,
                getResources().getDisplayMetrics()
        );
        // 定义九色渐变
        colors = new int[]{
                ContextCompat.getColor(getContext(), R.color.color_g_1),
                ContextCompat.getColor(getContext(), R.color.color_g_2),
                ContextCompat.getColor(getContext(), R.color.color_g_3),
                ContextCompat.getColor(getContext(), R.color.color_g_4),
                ContextCompat.getColor(getContext(), R.color.color_g_5),
                ContextCompat.getColor(getContext(), R.color.color_g_6),
                ContextCompat.getColor(getContext(), R.color.color_g_7),
                ContextCompat.getColor(getContext(), R.color.color_g_8),
                ContextCompat.getColor(getContext(), R.color.color_g_9)
        };

        // 计算每个颜色的位置（均匀分布）
        positions = new float[colors.length];
        for (int i = 0; i < colors.length; i++) {
            positions[i] = (float) i / (colors.length - 1);
        }

        currentColor = colors[0];

        roundedRectPath = new Path();
        rectF = new RectF();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        rectF.set(0, 0, w, h);
        updateRoundedRectPath();
    }

    private void updateRoundedRectPath() {
        roundedRectPath.reset();
        roundedRectPath.addRoundRect(rectF, cornerRadius, cornerRadius, Path.Direction.CW);
        roundedRectPath.close();
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        int width = getWidth();
        int height = getHeight();

        // 绘制渐变背景
        Shader shader = new LinearGradient(
                0, height, 0, 0,
                colors,
                positions,
                Shader.TileMode.CLAMP
        );
        paint.setShader(shader);

        canvas.clipPath(roundedRectPath);
        canvas.drawRect(0, 0, width, height, paint);

    }

    /**
     * 设置当前值（0.0-1.0）并更新颜色
     */
    public void setValue(float value) {
        // 限制值在0.0-1.0范围内
        this.value = Math.max(0f, Math.min(1f, value));

        // 计算当前值对应的颜色
        currentColor = calculateColor(this.value);

        // 重绘View
        invalidate();
    }

    /**
     * 根据值计算对应的颜色
     */
    private int calculateColor(float value) {
        if (value <= 0) return colors[0];
        if (value >= 1) return colors[colors.length - 1];

        // 找到值所在的区间
        for (int i = 0; i < positions.length - 1; i++) {
            if (value >= positions[i] && value <= positions[i + 1]) {
                // 计算区间内的插值比例
                float ratio = (value - positions[i]) / (positions[i + 1] - positions[i]);

                // 在两个颜色之间进行线性插值
                return interpolateColor(colors[i], colors[i + 1], ratio);
            }
        }

        return colors[0];
    }

    /**
     * 在两个颜色之间进行线性插值
     */
    private int interpolateColor(int color1, int color2, float ratio) {
        int alpha1 = Color.alpha(color1);
        int red1 = Color.red(color1);
        int green1 = Color.green(color1);
        int blue1 = Color.blue(color1);

        int alpha2 = Color.alpha(color2);
        int red2 = Color.red(color2);
        int green2 = Color.green(color2);
        int blue2 = Color.blue(color2);

        int alpha = (int) (alpha1 + ratio * (alpha2 - alpha1));
        int red = (int) (red1 + ratio * (red2 - red1));
        int green = (int) (green1 + ratio * (green2 - green1));
        int blue = (int) (blue1 + ratio * (blue2 - blue1));

        return Color.argb(alpha, red, green, blue);
    }
}